package trie;

import java.util.TreeMap;

public class Trie {

    private class Node {
        private boolean isWord;
        private TreeMap<Character, Node> next;

        private Node() {
            this.isWord = false;
            next = new TreeMap<>();
        }
    }

    private Node root;
    private int size;

    public Trie() {
        root = new Node();
        size = 0;
    }

    public void add(String word) {

        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null) {
                cur.next.put(c, new Node());
            }
            cur = cur.next.get(c);
        }

        size++;
        cur.isWord = true;

    }

    public boolean contains(String word) {

        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null) {
                return false;
            }
            cur = cur.next.get(c);
        }

        return cur.isWord;

    }

    //查看trie中是否包含前缀
    public boolean isPrefix(String prefix) {
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (cur.next.get(c) == null) {
                return false;
            }
            cur = cur.next.get(c);
        }

        return true;
    }

    //查看字典树中是否包含这个子串
    public boolean match(String subString) {
        Node cur = root;
        return match(root, subString, 0);
    }

    private boolean match(Node cur, String subString, int index) {

        if (index == subString.length()) {
            return cur.isWord;
        }

        char c = subString.charAt(index);
        if (c == '.') {

            for (char nextChar : cur.next.keySet()) {
                if (match(cur.next.get(nextChar), subString, index + 1)) {
                    return true;
                }
            }

            return false;

        } else {
            if (cur.next.get(c) == null) {
                return false;
            }

            return match(cur.next.get(c), subString, index + 1);
        }
    }

    public int getSize() {
        return size;
    }
}
